
from sqlalchemy import event
from typing import Optional, List
from sqlmodel import Field, SQLModel, Relationship
from sqlalchemy import event, text

from models.Base import BaseAndTimeAndWeight , StatusTypeEnum
from models.common import get_current_time

from enum import Enum

class depType(int, Enum):
    company = 0
    branch = 1
    departments = 2

class create_dept(SQLModel):
    parentId: Optional[int|None] = Field(default=None, title="父级部门", index=True, foreign_key="sys_department.id")
    name: Optional[str] = Field(max_length=30,title='部门名称')
    phone: str = Field(max_length=30,nullable=False,title='电话')
    principal: str = Field(max_length=30,nullable=False,title='负责人')
    email: Optional[str] = Field(max_length=255,nullable=False,title='邮箱')
    type: depType = Field(default=depType.company,title='部门类型', index=True)
    status: StatusTypeEnum = Field(default=StatusTypeEnum.NORMAL,title='状态', index=True)
    remark: Optional[str] = Field(max_length=255,title='备注')

class edit_dept(create_dept):
    id: int = Field(title='部门ID')

class Department(BaseAndTimeAndWeight,create_dept, table=True):
    __tablename__ = "sys_department"  # 确保表名一致
    parent: Optional["Department"] = Relationship(back_populates="children", sa_relationship_kwargs={"remote_side": "Department.id"})
    children: List["Department"] = Relationship(back_populates="parent")
    admins: list["Admin"] = Relationship(back_populates="department")

    @property
    def status_text(self)->str:
        if self.status == StatusTypeEnum.NORMAL:
            return "正常"
        elif self.status == StatusTypeEnum.ABNORMAL:
            return "关闭"
        return "未知"
    
    @property
    def type_text(self)->str:
        if self.type == depType.company:
            return "公司"
        elif self.type == depType.branch:
            return "分公司"
        elif self.type == depType.departments:
            return "部门"
        return "未知"

@event.listens_for(Department, 'before_update', propagate=True)
def timestamp_before_update(mapper, connection, target):
    target.updatetime = get_current_time()

# 监听 after_insert 事件
@event.listens_for(Department, 'after_insert', propagate=True)
def rank_after_insert(mapper, connection, target):
    if target.weight == 0:
        # 使用 connection 直接执行 SQL 语句更新 rank 为 id
        update_stmt = text("UPDATE sys_department SET `weight` = :weight WHERE id = :id")
        connection.execute(update_stmt, {"weight": target.id, "id": target.id})
